<?php

namespace App\Console\Commands\OpenShop;

use App\Models\OpenShop\Common\OpenShopProvinceTargetModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Facades\Excel;

class ImportProvinceTargetFromGy extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:import-province-target-from-gy';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导入省区年度目标-从观远';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private string $errMsg = '';
    private int    $year   = 0;


    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $list = collect(GuanyuanDataService::provinceTargets());

        $provinceNames = $list->pluck('省份')->unique()->values();
        $provinces     = OpenShopOrganizationRegionMappingModel::query()->whereIn('provinceName', $provinceNames)->get()
                                                               ->keyBy('provinceName');

        $totalMonthNewNum = 0;
        $lastProvince     = 0;

        $list = $list->map(function ($item, $row) use ($provinces, &$totalMonthNewNum, &$lastProvince) {


            list($provinceName, $yearNewNum, $yearCloseNum, $yearStockNum, $monthNewNum, $stockNum, $date) = array_values($item);

            $provinceCode = $provinces[$provinceName]['provinceCode'] ?? 0;
            if ($provinceCode != $lastProvince) {
                $totalMonthNewNum = 0;
                $lastProvince     = $provinceCode;
            }
            $totalMonthNewNum += $monthNewNum;

            $timestamp = strtotime($date);
            $yearMonth = date('Ym', $timestamp);

            if (!$this->year) {
                $this->year = date('Y', $timestamp);
            }

            if (!$provinceCode) {
                $this->errMsg .= "第{$row}行，找不到的省份名称: {$provinceName}" . PHP_EOL;
            }

            if (!$yearMonth) {
                $this->errMsg .= "第{$row}行，月份错误: {$date}" . PHP_EOL;
            }

            return [
                'provinceCode' => $provinceCode,
                'yearMonth'    => $yearMonth,
                'timestamp'    => $timestamp,
                'openNum'      => $monthNewNum,
                'closeNum'     => 0,
                'stockNum'     => $stockNum,
                'yearNewNum'   => $yearNewNum,
                'yearCloseNum' => $yearCloseNum,
                'yearStockNum' => $yearStockNum,
            ];

        })->filter();

        if ($this->errMsg) {
            dd($this->errMsg);
        }

        OpenShopProvinceTargetModel::query()->where('yearMonth', 'like', $this->year . '%')->delete();

        // 月份insert
        $monthData = $list->map(function ($item) {
            $item              = (new OpenShopProvinceTargetModel)->fill($item)->toArray();
            $item['createdAt'] = time();
            $item['updatedAt'] = time();
            return $item;
        })->values()->toArray();

        OpenShopProvinceTargetModel::query()->insert($monthData);

        // 年份insert
        $yearData = $list->keyBy('provinceCode')->map(function ($item) {

            return [
                'provinceCode' => $item['provinceCode'],
                'yearMonth'    => $this->year,
                'openNum'      => $item['yearNewNum'],
                'closeNum'     => $item['yearCloseNum'],
                'stockNum'     => $item['yearStockNum'],
                'createdAt'    => time(),
                'updatedAt'    => time(),
            ];
        });

        OpenShopProvinceTargetModel::query()->insert($yearData->toArray());

        $this->info('success');
    }
}

